package keqiang.com.kq_flutter_core_widget.channel;

import android.content.Context;

import java.util.HashMap;
import java.util.Map;

import androidx.annotation.NonNull;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;
import keqiang.com.kq_flutter_core_widget.interf.IKqRoute;
import keqiang.com.kq_flutter_core_widget.interf.IWxAuthCallback;

/**
 * flutter 第三方登录通道
 *
 * @author zhouzhuo810
 * @date 2023/3/13 17:49
 */
public class NativeThirdLoginChannel extends MethodChannel {
    
    // 通道id
    private static final String CHANNEL = "flutter.keqiang.com/thirdLogin";
    
    private static final String METHOD_WX_AUTH = "wxAuth";
    
    private Context mContext;
    
    public NativeThirdLoginChannel(@NonNull BinaryMessenger messenger) {
        super(messenger, CHANNEL);
        
        init();
    }
    
    
    public void setContext(Context context) {
        mContext = context;
    }
    
    private void init() {
        setMethodCallHandler((call, result) -> {
            switch (call.method) {
                case METHOD_WX_AUTH:
                    wxAuth(result);
                    break;
            }
        });
    }
    
    
    private void wxAuth(@NonNull Result result) {
        if (mContext == null || !(mContext instanceof IKqRoute)) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("code", "1");
            result.success(resultMap);
            return;
        }
        
        ((IKqRoute) mContext).wxLogin(new IWxAuthCallback() {
            @Override
            public void onSuccess(String authCode) {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("code", "0");
                resultMap.put("authCode", authCode);
                result.success(resultMap);
            }
            
            @Override
            public void onFail() {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("code", "1");
                result.success(resultMap);
            }
            
            @Override
            public void onNoInstall() {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("code", "2");
                result.success(resultMap);
            }
            
            @Override
            public void onCancel() {
                Map<String, Object> resultMap = new HashMap<>();
                resultMap.put("code", "-1");
                result.success(resultMap);
            }
        });
    }
}
